<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Models\Category as CategoryModel;

class CategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Category(), function (Grid $grid) {
            $grid->id->sortable();
            $grid->name;
            $grid->parent_id;
            $grid->is_directory->display(function ($value) {
                return $value ? '是' : '否';
            });
            $grid->level;
            $grid->path;
            $grid->created_at;
            $grid->updated_at->sortable();

            // 禁止查看
            $grid->actions(function ($actions) {
                $actions->disableView();
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description()['edit'] ?? trans('admin.edit'))
            ->body($this->form(true)->edit($id));
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($isEditing = false)
    {
        return Form::make(new Category(), function (Form $form) use($isEditing) {
            // 如果是编辑的情况
            if ($isEditing) {
                // 不允许用户修改[是否是目录] 和 [父类目] 字段的值
                $form->display('is_directory', '是否目录')->with(function ($value) {
                    return $value ? '是' : '否';
                });
                $form->display('parent.name', '父类目');
            } else {
                $form->radio('is_directory', '是否目录')
                    ->options(['1' => '是', '0' => '否'])
                    ->default('0')
                    ->rules('required');

                // 定义一个名为父类目的下拉框
                $form->select('parent_id', '父类目')->ajax('/api/categories');
            }
        });
    }

    // 定义下拉框搜索按钮
    public function apiIndex(Request $request)
    {
        $search = $request->input('q');
        $result = CategoryModel::query()
            ->where('is_directory', boolval($request->input('is_directory', true)))
            ->where('name', 'like', '%' . $search . '%')
            ->paginate();

        // getCollection() 方法是获取到这个分页里面的集合， setCollection() 就是把分页的数据替换
        $result->setCollection($result->getCollection()->map(function (CategoryModel $category) {
            return ['id' => $category->id, 'text' => $category->full_name];
        }));

        return $result;
    }
}
